﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Collection.Core;
using Collection.Entities;
using Collection.Utilities;
using System.Reflection;

namespace Collection.Platform
{
    /// <summary>
    /// 采集监视器对象
    /// </summary>
    public class Monitor
    {
        public Monitor()
        {
            ImageLoader.Loader.Complete += this.Oversee;
            ImageLoader.Loader.Unfinished += this.Oversee;

            CollectionServiceFactory.CatalogService.InsertToDB += this.Oversee<Catalog>;
            CollectionServiceFactory.CatalogService.UpdateToDB += this.Oversee<Catalog>;

            CollectionServiceFactory.PropertyService.InsertToDB += this.Oversee<Property>;
            CollectionServiceFactory.PropertyService.UpdateToDB += this.Oversee<Property>;

            CollectionServiceFactory.PropertyValueService.InsertToDB += this.Oversee<PropertyValue>;
            CollectionServiceFactory.PropertyValueService.UpdateToDB += this.Oversee<PropertyValue>;

            CollectionServiceFactory.MerchandiseService.InsertToDB += this.Oversee<Merchandise>;
            CollectionServiceFactory.MerchandiseService.UpdateToDB += this.Oversee<Merchandise>;
        }
        public void Oversee<T>(Object sender, CollectionEventArgs<T> e)
        {
            object value;
            Type entityType = e.Entity.GetType();
            var properties = entityType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            if (e.Status == OperateStatus.Insert)
            {
                Console.Write("插入：");
            }
            else if (e.Status == OperateStatus.Update)
            {
                Console.Write("插入：");
            }
            foreach (var p in properties)
            {
                value = p.GetValue(e.Entity, null);
                if (value != null)
                {
                    Console.WriteLine(string.Format("{0}:{1}", p.Name, value.ToString()));
                }
            }
            this.BreakRow();
        }

        public void Oversee(Object sender, ImageEventArgs e)
        {
            if (e.Status == OperateStatus.Success)
            {
                Console.WriteLine(string.Concat(e.Message, "    ", "下载完成"));
            }
            else if (e.Status == OperateStatus.Ignore)
            {
                Console.WriteLine(e.Message);
            }
            else
            {
                Console.WriteLine(e.Message);
            }
            this.BreakRow();
        }

        /// <summary>
        /// 输出格式化
        /// </summary>
        /// <param name="message">输出消息</param>
        private void BreakRow()
        {
            Console.WriteLine("——————————————");
        }
    }
}
